//ContractProductControllerTest
public without sharing class ContractHandler implements Triggers.Handler {

    public void handle() 
    {
        // Map<Id,String> errorMap = new Map<Id,String>();
        // Set<Id> oppIdSet = new Set<Id>();

        ///合同生效的时候 反写相关的业务机会到合同签订阶段
        if(Trigger.isAfter && Trigger.isUpdate)
        {
             Set<Id> oppIdSet = new Set<Id>();
             //合同变更的记录id 
             Id deleRTId  = Utils.getRecordTypeIdByDevNameAndObjName('DeleteContract','Contract__c');
             Id mconRTId = Utils.getRecordTypeIdByDevNameAndObjName('ChangeContract','Contract__c');
             Id terRTId = Utils.getRecordTypeIdByDevNameAndObjName('TerminalContract','Contract__c');
             Set<Id>conset =new Set<Id>();
            for(Contract__c c : (List<Contract__c>)Trigger.new){
                //System.debug(c.Id);
                Contract__c oldc = (Contract__c)Trigger.oldMap.get(c.Id);
                ///经销商合同记录类型id
                //Id rt = Utils.getRecordTypeIdByDevNameAndObjName('DealerContract','Contract__c');
                if(c.Status__c != oldc.Status__c && c.Status__c == '已推送OA'   && c.RecordTypeId  == mconRTId  )ContractCalcEquipmentUtil.mToOaBackToMainContract(c);

                if(c.Status__c != oldc.Status__c && c.Status__c == '已生效' ){
                    if(c.RecordTypeId  == mconRTId || c.RecordTypeId  == terRTId )conset.add(c.Id );
                    //合同变更审批通过 反写到主合同
                    System.debug('ContractHandler==>'+ c.RecordTypeId + ' '+mconRTId);
                    if( c.RecordTypeId  == mconRTId )ContractCalcEquipmentUtil.modifyBackToMainContract(c);
                    //合同仪器产品:已审批数量
                    Id contractId = c.RecordTypeId  == mconRTId ? c.MainContract__c : c.Id ;
                    System.debug('ContractHandler==>'+ contractId);
                   if( c.RecordTypeId  == terRTId ) ContractCalcEquipmentUtil.calcEquipmentNum(contractId);
                    // 合同审批通过后，获取合同下关联报价/测算的业务机会
                    oppIdSet.add(c.Opportunity__c);
                    if(c.RecordTypeId == deleRTId ) update new Contract__c(Id = c.MainContract__c, ActuallyDateStopDate__c = System.today());

                  

                }
            }
            //回写主要用户
            addMajorCustomer(conset);
           ContractProductHandler.upgradeStage(conset);
                // Map<Id,String > oppMap = new Map<Id,String >();
                // System.debug(oppIdSet);

                // for (Contract__c con : [select Id,Status__c ,Opportunity__c ,Opportunity__r.RecordType.DeveloperName  from Contract__c where Opportunity__c in: oppIdSet ]) {
                //     oppMap.put(con.Opportunity__c, con.Opportunity__r.RecordType.DeveloperName);
                //     if(con.Status__c  != '已生效')oppIdSet.remove(con.Opportunity__c);
                // }
                // List<Opportunity> oppList = new List<Opportunity>();
                // for (Id oid : oppIdSet ) {
                //     Opportunity o = new Opportunity();
                //     o.Id = oid;
                //     o.StageName =  oppMap.get(oid).equals('OverseaDearlerOpportunity') ?'合作确认'  :'合同签订'; 
                //     if(o.Id != null )oppList.add(o);        
                // }
               
                // if(oppList.size() > 0)update oppList;
                
        }


    }
    ///处理合同仪器产品:已审批数量
    /*public static void updateApplicationQuantity(Set<Id> cons ){
        List<ContractProduct__c> cpList = new List<ContractProduct__c>();
        for(ContractProduct__c cp: [select Id,Quantity__c,ApplicationQuantity__c from ContractProduct__c where Contract__c in:cons ]){
            cp.ApplicationQuantity__c = cp.Quantity__c;
            cpList.add(cp);

        }
        if(cpList.size() > 0)update cpList;

    }
    */


    ///在合同生效的时候将 合同仪器的终端客户 写入到经销商的 主要用户里
    public static void addMajorCustomer(Set<Id> cons){
        if(cons == null || cons.isEmpty())return;
        Map<String,MajorUserInfo__c > uMap  = new Map<String,MajorUserInfo__c>();
        Set<Id> dealers = new Set<Id>();
        Set<Id> accs  = new Set<Id>();
        for (ContractProduct__c cp  :[select EndCustomer__c ,Contract__r.Account__c from ContractProduct__c 
            where Contract__c in: cons  and Contract__r.Account__r.RecordType.DeveloperName = 'Dealer' and EndCustomer__c != null ] ) {
            MajorUserInfo__c m = new MajorUserInfo__c();
            m.Dealer__c = cp.Contract__r.Account__c;
            m.MajorCustomer__c = cp.EndCustomer__c;
            m.BackgroundImport__c= true;
            accs.add(m.MajorCustomer__c);
            dealers.add(m.Dealer__c);
            uMap.put(m.Dealer__c +'-' +m.MajorCustomer__c ,m);
        }

        if(uMap.isEmpty())return;
        for(MajorUserInfo__c m : [select Dealer__c,MajorCustomer__c from MajorUserInfo__c where Dealer__c in: dealers and MajorCustomer__c in:accs   ]){
            String key = m.Dealer__c +'-' +m.MajorCustomer__c;
            if(uMap.containsKey( key))uMap.remove(key);
        }
        if(!uMap.isEmpty())insert uMap.values();
    }


    ///在合同更新的时候带入信用期 信用额
    public static  void setCredt(List<Contract__c> cons){
        Set<Id> accset = new Set<Id>();
        Set<String> coms = new Set<String>();

        Map<String,String > companyMap = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c',true);
        for (Contract__c c : cons ) {
            if(c.Account__c != null )accset.add(c.Account__c);

            if(c.Corpcode__c != null)coms.add(companyMap.get(c.Corpcode__c));


        }
        for (AccountCredit__c ac :[select CreditLimit__c,NCCreditDeadline__c,Id,Company__c,Account__c
            from AccountCredit__c where Company__c in:coms and Account__c in:accset ] ) {
            for (Contract__c c: cons) {
                if(companyMap.get(c.Corpcode__c) == ac.Company__c && c.Account__c == ac.Account__c){
                    c.NCCreditDays__c = ac.NCCreditDeadline__c;
                   // c.CreditDays__c = ac.NCCreditDeadline__c;
                    c.Credit__c = ac.CreditLimit__c;
                }
            }

        }
        
    } 

    /// 


}